<template>
  <CustomDialog :options="options" @open="open" @confirm="handleConfirm()">
    <div class="wrapper">
      <div class="wrapper-left">
        <el-form
          ref="dialogFormRef"
          :model="formData"
          :rules="rules"
          label-width="80px"
          label-position="top"
        >
          <el-form-item label="标题" prop="title">
            <el-input
              v-model="formData['title']"
              placeholder="请输入"
              maxlength="30"
              show-word-limit
              type="textarea"
              clearable
            />
          </el-form-item>

          <el-form-item label="分类" prop="classification">
            <el-select
              v-model="formData['classification']"
              placeholder="请选择"
              :style="{ width: '100%' }"
              clearable
            >
              <el-option
                v-for="item in cateList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="模板编号" prop="templateId" v-show="false">
            <el-input v-model="formData['templateId']" placeholder="请输入" />
          </el-form-item>
        </el-form>
      </div>
      <!-- 渲染来源于SelectQCForm组件 -->
      <div id="wrapper-right">
        <div class="right-content">
          <el-form-item required>
            <template #label>
              <span class="text-dark text-df">选择模板</span>
            </template>
            <el-input
              v-model="searchTemplate"
              @change="handleFilterTemplate"
              :prefix-icon="Search"
              clearable
            />
          </el-form-item>
          <div class="flex flex-wrap justify-around">
            <div
              v-for="(item, index) in selectList"
              :key="index"
              class="select-card"
              :class="{
                'active-card': `${item.id}` === `${selectItem.id}`,
              }"
              @click="selectTemplate(item)"
            >
              <img class="title-icon" src="@/assets/images/plan/plan-icon.png" alt="" />
              <span class="over-title">{{ item.templateName }}</span></div
            >
            <div class="empty-box"></div>
          </div>
        </div>
      </div>
    </div>
  </CustomDialog>
</template>

<script setup>
  import { computed, nextTick, reactive, ref, watch, onMounted } from 'vue';
  import CustomDialog from '@/components/CustomDialog/index.vue';
  import { Search } from '@element-plus/icons-vue';
  import { ElMessage } from 'element-plus';
  import { useStore } from 'vuex';
  import { postHandbookRecordAdd } from '@/api/handbookRecord/index';

  const store = useStore();

  const deptId = store.state.user.deptId;
  const emit = defineEmits(['confirm', 'close']);

  const props = defineProps({
    options: {
      type: Object,
      default: () => {
        return {
          width: 948,
          title: '新建评价表',
          modal: false,
          visible: false,
          curItem: null,
          cate: [],
          templateList: [],
          typeId: '',
        };
      },
    },
  });
  const dialogOption = ref(props.options);

  const formData = ref({});
  const rules = {
    title: [{ required: true, message: '请输入', trigger: 'blur' }],
    classification: [{ required: true, message: '请选择', trigger: 'change' }],
    // templateId: [{ required: true, message: '请选择', trigger: 'change' }],
  };

  const searchTemplate = ref('');
  const dialogFormRef = ref();

  const cateList = computed(() => {
    return props.options.cate;
  });
  const open = () => {
    reset(dialogOption.value.curItem || {});
  };
  const templateList = computed(() => {
    return props.options.templateList;
  });
  const selectList = ref([]);
  const reset = (curItem) => {
    formData.value = {
      id: curItem.id,
    };
  };

  const close = () => {
    dialogOption.value.visible = false;
  };
  function resetForm() {
    nextTick(() => {
      searchTemplate.value = '';
      selectItem.value = {};
      dialogFormRef.value.resetFields();
    });
  }
  const handleConfirm = async (validatePass = false) => {
    if (!validatePass) {
      const valid = await dialogFormRef.value.validate();
      if (!valid) return;
      if (!formData.value['templateId']) {
        ElMessage({
          message: `请选择模板`,
          type: 'error',
        });
        return;
      }
      let result = await postHandbookRecordAdd({
        ...formData.value,
        deptId,
        type: props.options.typeId,
      });

      if (result.code === 200) {
        ElMessage({
          message: `新建成功`,
          type: 'success',
        });
        emit('confirm');
      }
    }
  };
  const selectItem = ref({});
  const selectTemplate = (item) => {
    console.log(item);
    selectItem.value = item;
    formData.value['templateId'] = item.id;
  };
  const handleFilterTemplate = (val) => {
    selectItem.value = {};
    selectList.value = templateList.value.filter((item) => {
      return item.templateName.includes(searchTemplate.value);
    });
  };

  watch(
    () => props.options.visible,
    (val) => {
      dialogOption.value.visible = val;
      resetForm();
      selectList.value = props.options.templateList;
    },
  );
  // watch(
  //   () => props.options.templateList,
  //   (val) => {
  //     selectList.value = val;
  //   },
  // );
</script>

<style lang="scss" scoped>
  .wrapper {
    display: flex;
    background: #f8f9f9;
    .wrapper-left {
      background: #fff;
      width: 260px;
      padding: 20px;
    }
    #wrapper-right {
      flex: 1;
      height: 350px;
      .right-content {
        width: 100%;
        padding-left: 20px;
        padding-right: 20px;
        margin: 20px auto;
        box-sizing: border-box;
      }
      .select-card {
        width: 48%;
        height: 54px;
        background-color: #fff;
        box-shadow: 0 1px 4px #f3fbf5;
        border-radius: 4px;
        display: flex;
        align-content: center;
        align-items: center;
        font-size: 14px;
        font-weight: 400;
        margin-bottom: 10px;
        color: #333;
        .title-icon {
          width: 30px;
          height: 30px;
          display: block;
          margin-right: 4px;
        }
        .over-title {
          max-width: 170px;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          -o-text-overflow: ellipsis;
          display: block;
        }
      }
      .active-card {
        box-shadow: 0px 0px 8px 0px #dfe7e7;
        background-color: #f5fdf8;
      }
      .empty-box {
        width: 48%;
        height: 50px;
        display: block;
      }
    }
  }
</style>
